package com.rran.study.chat.ops.service.accept;

import com.alibaba.fastjson.JSON;
import com.rran.study.chat.ops.pojo.socketmsg.MessageContext;
import com.rran.study.chat.ops.pojo.socketmsg.RegisterMsg;
import com.rran.study.chat.ops.enums.MessageType;
import com.rran.study.chat.ops.repository.ChannelFactory;
import com.rran.study.chat.ops.repository.ChannelResponsitory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author yy
 * @Type RegisterAcceptStrategyHandler.java
 * @Desc 用户第一次连接
 * @date 2020/8/7 10:55
 */
@AcceptHandler(messageType = MessageType.REGISTER)
@Component
@Slf4j
public class RegisterAcceptStrategyHandler extends AbstractAcceptStrategy<RegisterMsg> {

    @Override
    protected void doAccept(MessageContext<RegisterMsg> context) {
        RegisterMsg registerMsg = context.getChatMessage();
        String beanId = registerMsg.getBeanId();
        ChannelHandlerContext ctx = context.getCtx();
        //第一次连上将beanId和ctx绑定并缓存
        ChannelResponsitory.storeChannel(beanId,ctx);
        log.info(JSON.toJSONString(ChannelResponsitory.getChannelMap()));
        ctx.channel().writeAndFlush(new TextWebSocketFrame(beanId+"注册成功"));
    }

    private ChannelHandlerContext getTargetChannel(String target) {
        return ChannelFactory.getChannelHandlerContext(target);
    }
}
